#include <iostream>
#include <string>
#include <unistd.h>
#include <ctime>
#include <cassert>
#include "TcpServer.hpp"
#include "Protocol.hpp"
#include "Socket.hpp"

const std::string opers = "+-*/%^=";

static void Usage(std::string proc){
    std::cout << "\nUsage: " << proc << " serverip serverport\n"
              << std::endl;
}

int main(int args, char *argv[]){
    if (args != 3){
        Usage(argv[0]);
        exit(0); 
    }

    std::string serverip = argv[1];
    uint16_t serverport = std::stoi(argv[2]);

    MySocket sockfd;
    sockfd.Socket();
    bool r = sockfd.Connect(serverip, serverport);
    if(!r){
        return 1;
    }

    srand(time(nullptr) ^ getpid());
    int cnt = 1;

    std::string inbuffer_stream;
    while (cnt <= 5){
        int x = rand() % 10 + 1;
        int y = rand() % 10;
        char op = opers[rand() % opers.size()];

        std::cout << "==========" << "第" << cnt << "个请求..." << "==========" << std::endl;
        // 构建一个新的请求
        Request req(x, y, op);
        req.DebugPrint();
        std::string package;
        req.Serialize(&package);    // 序列化
        package = Encode(package);  // 添加报头

        // 发送请求
        write(sockfd.Fd(), package.c_str(), package.size());
        std::cout << "发送了一个请求报文: " << package << std::endl;

        // 接收响应
        char buffer[128];
        ssize_t n = read(sockfd.Fd(), buffer, sizeof(buffer));
        if(n > 0){
            buffer[n] = 0;
            inbuffer_stream += buffer;
            std::cout << "接收到一个响应报文: " << inbuffer_stream << std::endl;

            std::string content;
            bool r = Decode(inbuffer_stream, &content);  // 获取有效载荷
            assert(r);

            Response resp;
            r = resp.Deserialize(content);               // 反序列化
            assert(r);

            resp.DebugPrint();
        }
        std::cout << "================================================" << std::endl;
        cnt++;
        sleep(1);
    }

    // Response rp(1000, 0);
    // std::string s;
    // rp.Serialize(&s);
    // std::cout << s << std::endl;

    // s = Encode(s);
    // std::cout << s << std::endl;

    // Response temp;
    // std::string content;
    // Decode(s, &content);
    // std::cout << content << std::endl;

    // temp.Deserialize(content);
    // std::cout << temp._result << std::endl;
    // std::cout << temp._code << std::endl;
    return 0;
}